var util = require('../../utils/util.js');
var api = require('../../config/api.js');
var app = getApp();
Page({
  data: {
    categoryList: [],
    currentCategory: {},
    currentSubCategoryList: {},
    scrollLeft: 0,
    scrollTop: 0,
    goodsCount: 0,
    scrollHeight: 0,
    // 设备信息
    dev:{},
    openBottom:true,
    // 商品
    navList: [],
    goodsList: [],
    id: 0,
    /* currentCategory: {},
    scrollLeft: 0,
    scrollTop: 0,
    scrollHeight: 0, */
    page: 1,
    limit: 10,

    // 详情
    canShare: false,
    id: 0,
    goods: {},
    groupon: [], //该商品支持的团购规格
    grouponLink: {}, //参与的团购
    attribute: [],
    issueList: [],
    comment: [],
    brand: {},    
    attrName: [{
      name: 'temp',
      text: '温度',
      select: ''
    }, {
      name: 'sweet',
      text: '甜度',
      select: ''
    }, {
      name: 'dense',
      text: '浓度',
      select: ''
    }],
    formulaSelect:{
      temp:'',
      sweet:'',
      dense:''
    },
    specificationList: {},
    productList: [],
    relatedGoods: [],
    cartGoodsCount: 0,
    userHasCollect: 0,
    number: 1,
    checkedSpecText: '规格数量选择',
    tmpSpecText: '请选择规格数量',
    checkedSpecPrice: 0,
    openAttr: false, // 打开规格选择
    openShare: false,
    collect: false,
    shareImage: '',
    isGroupon: false, //标识是否是一个参团购买
    soldout: false,
    canWrite: false, //用户是否获取了保存相册的权限
    

    // 购物车
    bottomShow:true,
    cartShow:false,
    cartGoods: [],
    cartTotal: {
      "goodsCount": 0,
      "goodsAmount": 0.00,
      "checkedGoodsCount": 0,
      "checkedGoodsAmount": 0.00
    },
    isEditCart: false,
    checkedAllStatus: true,
    editCartList: [],
    hasLogin: false,
    hasMobile: false

  },
  onShow: function() {
    const dev = wx.getStorageSync('dev')
    if(dev&&dev!=={}){
      this.setData({
        dev: dev
      });    
      this.getCatalog(); 
    }else{
      wx.showModal({
        title: '未选择设备',
        content: '请先在首页扫描二维码绑定设备',
        showCancel: false,
        success (res) {
          if (res.confirm) {
            wx.switchTab({
              url: "/pages/index/index"
            });
          }
        }
      })
    }
    this.setData({
      hasLogin: app.globalData.hasLogin
    });
    const userInfo=wx.getStorageSync('userInfo')
    const hasMobile=userInfo.mobile && userInfo.mobile.length>8?true:false
    this.setData({
      hasLogin: app.globalData.hasLogin,
      hasMobile:hasMobile
    });
    // 页面显示
    if (app.globalData.hasLogin) {
      this.getCartList();
    }
    console.log(this.data.hasMobile)

  },
  onPullDownRefresh() {
    wx.showNavigationBarLoading() //在标题栏中显示加载
    this.getCatalog();
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新
  },
  // 加购物车
  addCart(e){
    console.log(e)
    const _goodsList = this.data.goodsList
    _goodsList[e.currentTarget.id].cartNumber=1;
    this.setData({
      goodsList: _goodsList
    });
    this.addToCart(e)
    console.log(this.data.goodsList)
  },
  // 修改购物车
  changeCart(e){
    console.log(e)
    const _goodsList = this.data.goodsList
    _goodsList[e.currentTarget.id].cartNumber=1;
    this.setData({
      goodsList: _goodsList
    });
    console.log(this.data.goodsList)
  },
  // 跳转详情
  goDetail(e){
    wx.navigateTo({
      url: "/pages/goods/goods?id="+e.currentTarget.id
    });
  },
  

  // 查分类
  getCatalog: function() {
    //CatalogList
    let that = this;
    wx.showLoading({
      title: '加载中...',
    });
    util.request(api.CatalogList,{
      devId:this.data.dev.devCode
    }).then(function(res) {
      that.setData({
        categoryList: res.data.categoryList,
        currentCategory: res.data.currentCategory/* ,
        currentSubCategoryList: res.data.currentSubCategory */
      });
      wx.hideLoading();
      that.getCurrentCategory(res.data.categoryList[0].id)
    });
    /* util.request(api.GoodsCount).then(function(res) {
      that.setData({
        goodsCount: res.data
      });
    }); */

  },
  // 查商品
  getCurrentCategory: function(id) {
    let that = this;
    util.request(api.GoodsList, {
      categoryId: id,
      page: that.data.page,
      limit: that.data.limit,
      devId:that.data.dev.devCode
    })
      .then(function(res) {
        that.setData({
          currentCategory: {id:id},
          goodsList: res.data.list
        });
      });
  },
  onReady: function() {
    // 页面渲染完成
  },
  onHide: function() {
    // 页面隐藏
  },
  onUnload: function() {
    // 页面关闭
  },
  switchCate: function(event) {
    console.log(event)
    var that = this;
    var currentTarget = event.currentTarget;
    if (this.data.currentCategory.id == event.currentTarget.dataset.id) {
      return false;
    }

    this.getCurrentCategory(event.currentTarget.dataset.id);
  },
  // -------------------详情-----------------

  // 规格选择
  clickSkuValue: function(event) {
    console.log(event)
    const eventArr = event.currentTarget.id.split("-")
    let that = this;
    let specName = event.currentTarget.dataset.name;
    let specValueId = event.currentTarget.dataset.valueId;

    //判断是否可以点击

    //TODO 性能优化，可在wx:for中添加index，可以直接获取点击的属性名和属性值，不用循环
    let _specificationList = this.data.specificationList;
    _specificationList[eventArr[0]].forEach(element => {
      element.checked = false;
    });
      _specificationList[eventArr[0]][eventArr[1]].checked = true;
      var _formulaSelect=this.data.formulaSelect
      _formulaSelect[eventArr[0]]=_specificationList[eventArr[0]][eventArr[1]].id
   console.log(_formulaSelect)

    /* for (let i = 0; i < _specificationList.length; i++) {
      if (_specificationList[i].name === specName) {
        for (let j = 0; j < _specificationList[i].valueList.length; j++) {
          if (_specificationList[i].valueList[j].id == specValueId) {
            //如果已经选中，则反选
            if (_specificationList[i].valueList[j].checked) {
              _specificationList[i].valueList[j].checked = false;
            } else {
              _specificationList[i].valueList[j].checked = true;
            }
          } else {
            _specificationList[i].valueList[j].checked = false;
          }
        }
      }
    } */
    this.setData({
      specificationList: _specificationList,
      formulaSelect: _formulaSelect
    });
    //重新计算spec改变后的信息
    // this.changeSpecInfo();

    //重新计算哪些值不可以点击
  },
  //添加到购物车
  addToCart: function(e) {
    console.log('添加到购物车')
    var that = this;
    if (this.data.openAttr == false) {
     //打开规格选择窗口
      const initFormula={
        temp:'',
        sweet:'',
        dense:''
      }
      //清空已选规格
      this.setData({
        openAttr:true,
        formulaSelect:initFormula,        
        bottomShow: false
      });
      this.getGoodsInfo(e)
    } else {
      // 是否选规格
      var formulaArr = Object.keys(this.data.specificationList)
      console.log(formulaArr)
      var isValid = true
      formulaArr.forEach(element => {
        if(this.data.formulaSelect[element] === ""){
          isValid =false
        }
      });
      console.log(isValid)
      if(!isValid){
        util.showErrorToast('请选择完整规格');
        return false;
      }
      //提示选择完整规格
      /* if (!this.isCheckedAllSpec()) {
        util.showErrorToast('请选择完整规格');
        return false;
      } */
      //添加到购物车 productId: checkedProduct.id
      var tmpFormula=[]
      Object.values(this.data.formulaSelect).forEach(function(ele,i){
          if(ele.length!=''){
            tmpFormula.push(ele);
          }
      })
      util.request(api.CartAdd, {
          goodsId: this.data.goods.id,
          number: this.data.number,
          formulaAttrIds: tmpFormula
        }, "POST")
        .then(function(res) {
          let _res = res;
          if (_res.errno == 0) {
            wx.showToast({
              title: '添加成功'
            });
            that.getCartList();
            that.setData({
              openAttr: false,
              cartGoodsCount: _res.data,
              bottomShow: true
            });
            if (that.data.userHasCollect == 1) {
              that.setData({
                collect: true
              });
            } else {
              that.setData({
                collect: false
              });
            }
          } else {
            util.showErrorToast(_res.errmsg);
          }

        });
    }

  },

  cutNumber: function() {
    this.setData({
      number: (this.data.number - 1 > 1) ? this.data.number - 1 : 1
    });
  },
  addNumber: function() {
    this.setData({
      number: this.data.number + 1
    });
  },
  switchAttrPop: function() {
    if (this.data.openAttr == false) {
      this.setData({
        openAttr: !this.data.openAttr
      });
    }
  },
  closeAttr: function(e) {    
      this.setData({
        openAttr: false,
        bottomShow: true
      });
  },
  // 获取商品信息
  getGoodsInfo: function(e) {
    let that = this;
    util.request(api.GoodsDetail, {
      id: this.data.goodsList[e.currentTarget.id].id
    }).then(function(res) {
      if (res.errno === 0) {

        let _specificationList = res.data.formula

        that.setData({
          goods: res.data.info,
          attribute: res.data.attribute,
          issueList: res.data.issue,
          // comment: res.data.comment,
          brand: res.data.brand,
          specificationList: res.data.formula,
          productList: res.data.productList,
          userHasCollect: res.data.userHasCollect,
          shareImage: res.data.shareImage,
          checkedSpecPrice: res.data.info.retailPrice,
          // groupon: res.data.groupon,
          canShare: res.data.share,
        });

        if (res.data.userHasCollect == 1) {
          that.setData({
            collect: true
          });
        } else {
          that.setData({
            collect: false
          });
        }

        // WxParse.wxParse('goodsDetail', 'html', res.data.info.detail, that);

      }
    });
  },
  // -----------购物车---------------------
  goLogin() {
    wx.navigateTo({
      url: "/pages/auth/login/login"
    });
  },
  getCartList: function() {
    let that = this;
    util.request(api.CartList).then(function(res) {
      if (res.errno === 0) {
        var redData=res.data.cartList
        // 配方
        redData.forEach(function(e){
          e.formula=Array.from(JSON.parse(e.formulaAttrJson), (v) => v.unitName).toString()   
        })
        that.setData({
          cartGoods:  redData,
          cartTotal: res.data.cartTotal
        });

        that.setData({
          checkedAllStatus: that.isCheckedAll()
        });
      }
    });
  },
  isCheckedAll: function() {
    //判断购物车商品已全选
    return this.data.cartGoods.every(function(element, index, array) {
      if (element.checked == true) {
        return true;
      } else {
        return false;
      }
    });
  },
  doCheckedAll: function() {
    let checkedAll = this.isCheckedAll()
    this.setData({
      checkedAllStatus: this.isCheckedAll()
    });
  },
  checkedItem: function(event) {
    let itemIndex = event.target.dataset.itemIndex;
    let that = this;

    let productIds = [];
    productIds.push(that.data.cartGoods[itemIndex].id);
    if (!this.data.isEditCart) {
      util.request(api.CartChecked, {
        ids: productIds,
        isChecked: that.data.cartGoods[itemIndex].checked ? 0 : 1
      }, 'POST').then(function(res) {
        if (res.errno === 0) {
          that.setData({
            cartGoods: res.data.cartList,
            cartTotal: res.data.cartTotal
          });
        }

        that.setData({
          checkedAllStatus: that.isCheckedAll()
        });
      });
    } else {
      //编辑状态
      let tmpCartData = this.data.cartGoods.map(function(element, index, array) {
        if (index == itemIndex) {
          element.checked = !element.checked;
        }

        return element;
      });

      that.setData({
        cartGoods: tmpCartData,
        checkedAllStatus: that.isCheckedAll(),
        'cartTotal.checkedGoodsCount': that.getCheckedGoodsCount()
      });
    }
  },
  getCheckedGoodsCount: function() {
    let checkedGoodsCount = 0;
    this.data.cartGoods.forEach(function(v) {
      if (v.checked === true) {
        checkedGoodsCount += v.number;
      }
    });
    console.log(checkedGoodsCount);
    return checkedGoodsCount;
  },
  checkedAll: function() {
    let that = this;

    if (!this.data.isEditCart) {
      var productIds = this.data.cartGoods.map(function(v) {
        return v.id;
      });
      util.request(api.CartChecked, {
        ids: productIds,
        isChecked: that.isCheckedAll() ? 0 : 1
      }, 'POST').then(function(res) {
        if (res.errno === 0) {
          console.log(res.data);
          that.setData({
            cartGoods: res.data.cartList,
            cartTotal: res.data.cartTotal
          });
        }

        that.setData({
          checkedAllStatus: that.isCheckedAll()
        });
      });
    } else {
      //编辑状态
      let checkedAllStatus = that.isCheckedAll();
      let tmpCartData = this.data.cartGoods.map(function(v) {
        v.checked = !checkedAllStatus;
        return v;
      });

      that.setData({
        cartGoods: tmpCartData,
        checkedAllStatus: that.isCheckedAll(),
        'cartTotal.checkedGoodsCount': that.getCheckedGoodsCount()
      });
    }

  },
  editCart: function() {
    var that = this;
    if (this.data.isEditCart) {
      this.getCartList();
      this.setData({
        isEditCart: !this.data.isEditCart
      });
    } else {
      //编辑状态
      let tmpCartList = this.data.cartGoods.map(function(v) {
        v.checked = false;
        return v;
      });
      this.setData({
        editCartList: this.data.cartGoods,
        cartGoods: tmpCartList,
        isEditCart: !this.data.isEditCart,
        checkedAllStatus: that.isCheckedAll(),
        'cartTotal.checkedGoodsCount': that.getCheckedGoodsCount()
      });
    }

  },
  updateCart: function(productId, goodsId, number, id) {
    let that = this;

    util.request(api.CartUpdate, {
      productId: productId,
      goodsId: goodsId,
      number: number,
      id: id
    }, 'POST').then(function(res) {
      that.setData({
        checkedAllStatus: that.isCheckedAll()
      });
      that.getCartList();
    });

  },
  changeNumber: function(event) {
    console.log(event)

    let itemIndex = event.target.dataset.itemIndex;
    let cartItem = this.data.cartGoods[itemIndex];
    let number = event.detail //(cartItem.number - 1 > 1) ? cartItem.number - 1 : 1;
    cartItem.number = number;
    if(number === 0){
      this.deleteCart([cartItem.id])
    }else{
      this.setData({
        cartGoods: this.data.cartGoods
      });
      this.updateCart(cartItem.productId, cartItem.goodsId, number, cartItem.id);
    }
  },
  cutNumber: function(event) {

    let itemIndex = event.target.dataset.itemIndex;
    let cartItem = this.data.cartGoods[itemIndex];
    let number = (cartItem.number - 1 > 1) ? cartItem.number - 1 : 1;
    cartItem.number = number;
    this.setData({
      cartGoods: this.data.cartGoods
    });
    this.updateCart(cartItem.productId, cartItem.goodsId, number, cartItem.id);
  },
  addNumber: function(event) {
    let itemIndex = event.target.dataset.itemIndex;
    let cartItem = this.data.cartGoods[itemIndex];
    let number = cartItem.number + 1;
    cartItem.number = number;
    this.setData({
      cartGoods: this.data.cartGoods
    });
    this.updateCart(cartItem.productId, cartItem.goodsId, number, cartItem.id);

  },
  // 绑定手机号
  bindPhoneNumber: function(e) {
    console.log('bindPhoneNumber')
    console.log(e)

    const userInfo=wx.getStorageSync('userInfo')

    if (!userInfo ) {
      wx.showToast({
        title: '绑定失败：请先登录',
        icon: 'none',
        duration: 2000
      });
      // 拒绝授权
      return;
    }
    /* console.log('AuthBindPhone request')
    console.log({
      userId:userInfo.userId,
      iv: e.detail.iv,
      encryptedData: e.detail.encryptedData
    }) */
    // debugger
    var that=this;
    util.request(api.AuthBindPhone, {
      userId:userInfo.userId,
      iv: e.detail.iv,
      encryptedData: e.detail.encryptedData
    }, 'POST').then(function(res) {
       
      if (res.errno === 0) {

        wx.setStorageSync('userInfo', userInfo);
        that.setData({
          hasMobile:true
        });
        // 去结算
        that.checkoutOrder()
      }else{
        wx.showModal({
          title: '提示',
          content:res.errmsg,
          showCancel:false
        });
        return false
      }
    });
  },
  checkoutOrder: function() {
    //获取已选择的商品
    let that = this;
    var checkedGoods = this.data.cartGoods.filter(function(element, index, array) {
      if (element.checked == true) {
        return true;
      } else {
        return false;
      }
    });
    if (checkedGoods.length <= 0) {
      return false;
    }

    // storage中设置了cartId，则是购物车购买
    try {
      wx.setStorageSync('cartId', 0);
      var cartIds=Array.from(checkedGoods, (v) => v.id)
      console.log(cartIds)
      wx.setStorageSync('cartIds', cartIds);
      wx.navigateTo({
        url: '/pages/checkout/checkout'
      })
    } catch (e) {}

  },
  deleteCart: function(productIds) {
    //获取已选择的商品
   let that = this;

    /* let productIds = this.data.cartGoods.filter(function(element, index, array) {
      if (element.checked == true) {
        return true;
      } else {
        return false;
      }
    });

    if (productIds.length <= 0) {
      return false;
    }

    productIds = productIds.map(function(element, index, array) {
      if (element.checked == true) {
        return element.productId;
      }
    }); */


    util.request(api.CartDelete, {
      ids: productIds
    }, 'POST').then(function(res) {
      if (res.errno === 0) {
        console.log(res.data);
        let cartList = res.data.cartList.map(v => {
          v.checked = false;
          return v;
        });

        that.setData({
          cartGoods: cartList,
          cartTotal: res.data.cartTotal
        });
      }

      that.setData({
        checkedAllStatus: that.isCheckedAll()
      });
    });
  },
  closeCart(){
    this.setData({
      cartShow: false
    });
  },
  showCart(){
    // var isShow=this.data.cartShow?false:true;
    this.setData({
      cartShow: !this.data.cartShow
    });
  }
})